package server;

import lombok.Data;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: zhouzhijun
 * @Date: 2021/4/22 15:15
 */
@Data
public class Context {
    private List<Wrapper> wrappers = new ArrayList<>();
    private String context;
    private String workDir;
    private MyClassLoader myClassLoader;

    public void init() {
        myClassLoader = new MyClassLoader(workDir + File.separator + context);
        try {
            loadClasses("");
            loadServlet();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    private void loadClasses(String scanPackage) throws ClassNotFoundException {
        String basePack = workDir + File.separator + context;
        String scanPackagePath = basePack + scanPackage;
        scanPackagePath = scanPackagePath.replaceAll("\\.", "/");
        File pack = Path.of(scanPackagePath).toFile();

        File[] files = pack.listFiles();
        if (files == null) {
            return;
        }
        for (File file : files) {
            // 子package
            if (file.isDirectory()) {
                // 递归
                loadClasses(scanPackage + "." + file.getName());
            } else if (file.getName().endsWith(".class")) {
                String className = scanPackage + "." + file.getName().replaceAll(".class", "");
                className = className.substring(1);
                System.out.println(className);
                myClassLoader.findClass(className);
            }
        }


    }


    /**
     * 加载解析web.xml，初始化Servlet
     */
    private void loadServlet() throws IOException {
        String basePack = workDir + "/" + context;
        InputStream resourceAsStream = Files.newInputStream(Path.of(basePack + "/web.xml"));
        SAXReader saxReader = new SAXReader();

        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();

            List<Element> selectNodes = rootElement.selectNodes("//servlet");
            for (int i = 0; i < selectNodes.size(); i++) {
                Element element = selectNodes.get(i);
                // <servlet-name>lagou</servlet-name>
                Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
                String servletName = servletnameElement.getStringValue();
                // <servlet-class>server.LagouServlet</servlet-class>
                Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
                String servletClass = servletclassElement.getStringValue();


                // 根据servlet-name的值找到url-pattern
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                // /lagou

                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();
                Class<?> aClass = myClassLoader.loadClass(servletClass);
                wrappers.add(new Wrapper(urlPattern, (HttpServlet) aClass.newInstance()));
            }


        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }
}
